//
//  HomeViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/5/26.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit
import SVProgressHUD
import swiftScan

class HomeViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    @IBOutlet weak var mainCollectionView: UICollectionView!
    @IBOutlet weak var logoutItemButton: UIBarButtonItem!
    
    @IBOutlet weak var tjjWelcomeLabel: UILabel!
    @IBOutlet weak var deviceNameLabel: UILabel!
    @IBOutlet weak var deviceSerialNumberLabel: UILabel!
    @IBOutlet weak var renameButton: UIButton!
    

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setUpView()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        self.setUpNavigationLabel()
        
    }
    
    // MARK: - 初始化
    func setUpView() {
        
        // MARK: 是否已登录
        self.login()
        
        // MARK: collectionView设置代理
        self.mainCollectionView.delegate = self
        self.mainCollectionView.dataSource = self
        
        //MARK: nav上的三行
        self.tjjWelcomeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_TJJ_WELCOME, comment: "") + "()"
        self.deviceNameLabel.text = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_NAME, comment: "") + ":"
        self.deviceSerialNumberLabel.text = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":"
        
        //修改按钮
        self.renameButton.setTitle(NSLocalizedString(LOCALIZABLE_STRING_RENAME, comment: ""), for: .normal)
        
        
    }
    
    
    // MARK: - collectionView DataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 13
        
    }
    
    // MARK: - cell设置
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell:HomeViewCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeViewCollectionViewCell", for: indexPath) as! HomeViewCollectionViewCell
        
        let pathString = Bundle.main.path(forResource: "HomeViewPlist", ofType: "plist")
        
        let cellDictionary = NSDictionary.init(contentsOfFile: pathString!)
        
        let cellInfoDict:NSDictionary = cellDictionary?.value(forKey: "\(indexPath.row)") as! NSDictionary
        
        let imageName:String = cellInfoDict.value(forKey: "icon") as! String
        
        let iconImage = UIImage.init(named: imageName)
        
        let cellNameKey = cellInfoDict.value(forKey: "name") as! String
        
        let cellName = NSLocalizedString(cellNameKey, comment: "")
        
        cell.setUpViewCell(iconImage: iconImage!, nameString: cellName)
        
        return cell
    }
    
    // MARK: - cell之间距离
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        
        return (STATIC_VALUE_SCREEN_WIDTH - 20.0 - 240.0) / 4.0
        
    }
    
    // MARK: - 选中collectionView
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let cell:HomeViewCollectionViewCell = collectionView.cellForItem(at: indexPath) as! HomeViewCollectionViewCell
        
        switch cell.cellName.text {
        case NSLocalizedString(LOCALIZABLE_STRING_ABOUT_APP, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "AboutViewController", bundle: Bundle.main)
            
            let aboutViewController:AboutViewController = storyboard.instantiateViewController(withIdentifier: "AboutViewController") as! AboutViewController
            
            aboutViewController.hidesBottomBarWhenPushed = true
            
            self.show(aboutViewController, sender: nil)
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_ADD_DEVICE, comment: "")?:
            
            // TODO: 相机权限
            
            var style = LBXScanViewStyle()
            style.centerUpOffset = 44;
            style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
            style.photoframeLineW = 3;
            style.photoframeAngleW = 18;
            style.photoframeAngleH = 18;
            style.isNeedShowRetangle = false;
            
            style.anmiationStyle = LBXScanViewAnimationStyle.LineMove;
            
            //qq里面的线条图片
            style.animationImage = UIImage(named: "qrcode_scan_light_green")
            
            let vc = LBXScanViewController();
            vc.scanStyle = style
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            
            
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_REAL_TIME_TRACK, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "RealTimeTrackController", bundle: Bundle.main)
            
            let real = storyboard.instantiateViewController(withIdentifier: "RealTimeTrackViewController")
            
            real.hidesBottomBarWhenPushed = true
            
            self.show(real, sender: nil)
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_MAP_SELECT, comment: "")?:
            
            let mapSelectController = MapSelectViewController.init()
            
            mapSelectController.hidesBottomBarWhenPushed = true
            
            self.show(mapSelectController, sender: nil)
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_ONLINE_COMMAND, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "SentCommand", bundle: Bundle.main)
            
            let sentCommandViewController = storyboard.instantiateViewController(withIdentifier: "sentCommandViewController")
            
            sentCommandViewController.hidesBottomBarWhenPushed = true
            
            self.show(sentCommandViewController, sender: nil)
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_MONITOR_CENTER, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "MonitorCenter", bundle: Bundle.main)
            
            let monitorCenterViewController = storyboard.instantiateViewController(withIdentifier: "MonitorCenterViewController")
            
            monitorCenterViewController.hidesBottomBarWhenPushed = true
            
            self.show(monitorCenterViewController, sender: nil)
            
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_LOCATION_HISTORY, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "LocationHistory", bundle: Bundle.main)
            
            let dateSelectViewController = storyboard.instantiateViewController(withIdentifier: "LHDateSelectViewController")
            
            dateSelectViewController.hidesBottomBarWhenPushed = true
            
            self.show(dateSelectViewController, sender: nil)
            
            break
            
            
        case NSLocalizedString(LOCALIZABLE_STRING_BASE_STATION_LOCATION, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "BaseStationLocation", bundle: Bundle.main)
            
            let baseStationLocationViewController = storyboard.instantiateViewController(withIdentifier: "BaseStationLocationViewController")
            
            baseStationLocationViewController.hidesBottomBarWhenPushed = true
            
            self.show(baseStationLocationViewController, sender: nil)
            
            
            break
            
            
        case NSLocalizedString(LOCALIZABLE_STRING_GPS_LOCATION, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "GPSLocation", bundle: Bundle.main)
            
            let gpsLocationViewController = storyboard.instantiateViewController(withIdentifier: "GPSLocationViewController")
            
            gpsLocationViewController.hidesBottomBarWhenPushed = true
            
            self.show(gpsLocationViewController, sender: nil)
            
            
            break
            
        case NSLocalizedString(LOCALIZABLE_STRING_LOOKING_FOR_CAR, comment: "")?:
            
            let storyboard = UIStoryboard.init(name: "LookingForCar", bundle: Bundle.main)
            
            let lookingForCarViewController = storyboard.instantiateViewController(withIdentifier: "LookingForCarViewController")
            
            lookingForCarViewController.hidesBottomBarWhenPushed = true
            
            self.show(lookingForCarViewController, sender: nil)
            
            break
            
        default:
            break
        }
        
        
    }
   
    
    // MARK: - 登出
    @IBAction func logoutThisAccount(_ sender: UIBarButtonItem) {
        
        if (self.presentingViewController != nil) {
            
            self.dismiss(animated: true, completion: nil)
            
        }else{
            
            let storyBoard = UIStoryboard.init(name: "LoginViewController", bundle: Bundle.main)
            
            let navigationController = storyBoard.instantiateViewController(withIdentifier: "FirstViewNavigationController")
            
            self.present(navigationController, animated: true, completion: nil)
            
        }
        
        UserDefaults.standard.set(false, forKey: USER_DEFAULTS_IS_LOGON)
        
    }
    
    // MARK: - 登录
    func login() {
        
        if (self.presentingViewController != nil) {
            
            self.setUpNavigationLabel()
            
            return
            
        }else{
            
            let userName:String = UserDefaults.standard.value(forKey: USER_DEFAULTS_USER_NAME) as! String
            
            let password:String = UserDefaults.standard.value(forKey: USER_DEFAULTS_PASSWORD) as! String
            
            SVProgressHUD.show()
            
            self.logoutItemButton.isEnabled = false
            
            NetworkCommand.login(userName: userName, password: password, success: { (response) in
                
                NetworkCommand.GetDevicesByAccount(id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                    
                    
                    
                    if ((response as? NSArray) == nil) {
                        
                        SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_LOGIN_FAILED, comment: ""))
                        SVProgressHUD.dismiss(withDelay: 1)
                        
                        self.logoutItemButton.isEnabled = true
                        
                        return
                        
                    }
                    
                    let array:NSArray = response as! NSArray
                    
                    if array.count > 0{
                        
                        let dict:NSDictionary = array[0] as! NSDictionary
                        
                        UserModel.userModel.selectedDeviceSerialNumber = (dict.value(forKey: NETWORK_COMMAND_KEY_SERIAL_NUMBER) as? String) ?? ""
                        
                    }
                    
                    SVProgressHUD.dismiss()
                    
                    self.setUpNavigationLabel()
                    
                    self.logoutItemButton.isEnabled = true
                    
                }, failure: { (Error) in
                    
                    SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_LOGIN_FAILED, comment: ""))
                    SVProgressHUD.dismiss(withDelay: 1)
                    
                    self.logoutItemButton.isEnabled = true
                })
                
                
                
            }) { (Error) in
                
                SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_LOGIN_FAILED, comment: ""))
                
                SVProgressHUD.dismiss(withDelay: 1)
                
                self.logoutItemButton.isEnabled = true
                
            }
            
        }
        
        

        
    }
    
    
    // MARK: - 获取设备Array,并设置selectedDeviceSerialNumber
    func getDeviceByAccoutToSetSelectedDeviceSerialNumber(){
        
        NetworkCommand.GetDevicesByAccount(id: nil, clientType: nil, tokenPass: nil, success: { (response) in
            
        }) { (Error) in
            
        }
        
    }
    
    // MARK: - 设置NAV上的三个label
    func setUpNavigationLabel() {
        
        // MARK: 获取设备名
        var deviceName = ""
        
        if (UserModel.userModel.devicesByAccountArray != nil) {
            
            if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                
                if !(UserModel.userModel.selectedDeviceSerialNumber.isEmpty) {
                    
                    for dict in UserModel.userModel.devicesByAccountArray! {
                        
                        let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                        
                        let serialNumber:String = devicesByAccount?.SerialNumber ?? ""
                        
                        if serialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                            
                            deviceName = devicesByAccount?.DisplayName ?? serialNumber
                            
                            
                        }
                        
                        
                    }
                    
                }

                
            }
            
        }
        
        
        if deviceName.isEmpty {
            
            self.renameButton.isHidden = true
            
        }else{
            
            self.renameButton.isHidden = false
            
        }
        
        self.tjjWelcomeLabel.text = NSLocalizedString(LOCALIZABLE_STRING_TJJ_WELCOME, comment: "") + "(\(UserModel.userModel.userName!))"
        self.deviceNameLabel.text = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_NAME, comment: "") + ": " + deviceName
        self.deviceSerialNumberLabel.text = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ": " + UserModel.userModel.selectedDeviceSerialNumber
    }

    // MARK: - 改名
    @IBAction func selectedDeviceRename(_ sender: UIButton) {
        
        let alertController = UIAlertController.init(title: LOCALIZABLE_STRING_RENAME, message: nil, preferredStyle: .alert)
        
        let range = self.deviceNameLabel.text?.range(of: ": ")
        
        
        alertController.addTextField { (textfield) in
            
            textfield.text = self.deviceNameLabel.text?.substring(from: (range?.upperBound)!)
            
        }
        
        let alertTextfield = alertController.textFields?.first
        
        let confirmAction = UIAlertAction.init(title: LOCALIZABLE_STRING_CONFIRM, style: .destructive) { (UIAlertAction) in
            
            SVProgressHUD.show()
            
            NetworkCommand.updateDeviceAttribute(serialNumber: nil, id: nil, clientType: nil, tokenPass: nil, iconUrl: nil, driver: nil, licensePlate: nil, displayName: alertTextfield?.text, success: { (response) in
                
                self.setUpNavigationLabel()
                
                SVProgressHUD.dismiss()
                
            }, failure: { (Error) in
                
                SVProgressHUD.showError(withStatus: "")

                SVProgressHUD.dismiss(withDelay: 1)
                
            })
            
        }
        
        let cancelAction = UIAlertAction.init(title: LOCALIZABLE_STRING_CANCEL, style: .cancel, handler: nil)
        
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
        
        
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
